<?php

namespace App\Models;

use App\ModelFilters\Qh_KnowledgeFilter;
use App\Service\Redis\RedisBaseService;
use DB;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\Auth;
use function PHPUnit\Framework\isNull;

class Qh_Knowledge extends BaseModel
{
    protected $table = 'qh_knowledge';

    protected $guarded = [];

    protected $appends = ['userHas', 'learnPeopleCount', 'userLearnQuestionCount', 'userQuestionRate', 'parentName', 'courseName', 'kaoshiResult', 'kaoshiResultId', 'hasKoashiModeChild'];

    /**
     * 试题总数
     * @return int
     */
    //public function getQuestionCountAttribute(): int
    //{
    //    return Qh_Question::where('courseId', $this->id)->count();
    //}

    /**
     * 用户答题正确率
     */
    public function getUserQuestionRateAttribute()
    {
        $rate = 0;
        if (Auth::guard('api')->check()) {
            $user = Auth::guard('api')->user();

            $ids = [$this->id];
            if ($this->level == 1) {
                $ids = Qh_Knowledge::where('parentId', $this->id)->pluck('id')->toArray();
            }
            if ($ids) {
                // 所有错题
                $wrongCount = DB::table('qh_user_question_logs')
                    ->where('userId', $user->id)
                    ->whereIn('knowledgeId', $ids)->where('result', 2)->count();
                // 所有对题
                $rightCount = DB::table('qh_user_question_logs')
                    ->where('userId', $user->id)
                    ->whereIn('knowledgeId', $ids)->where('result', 1)->count();
            }else {
                $wrongCount = 0;
                $rightCount = 0;
            }

            $sum = $rightCount + $wrongCount;
            if ($sum > 0) {
                $rate = round(($rightCount / $sum) * 100, 2);
            }
        }
        return $rate;
    }

    /**
     * 在学总数
     * @return int
     * @throws \RedisException
     */
    public function getLearnPeopleCountAttribute(): int
    {
        return (new RedisBaseService())->getLearnUserCountInKnowledge($this->id);
    }

    /**
     * 当前用户已学的试题数量
     * @return int
     * @throws \RedisException
     */
    public function getUserLearnQuestionCountAttribute(): int
    {
        $count = 0;
        if (Auth::guard('api')->check()) {
            $user = Auth::guard('api')->user();
            // 1级知识点
            if (is_null($this->parentId)) {
                $level2Ids = DB::table('qh_knowledge')->where('parentId', $this->id)->pluck('id')->toArray();
                foreach ($level2Ids as $level2Id) {
                    $count += (new RedisBaseService())->getUserLearnQuestionCountByKnowledge($user->id, $level2Id);
                }
            }else {
                $count = (new RedisBaseService())->getUserLearnQuestionCountByKnowledge($user->id, $this->parentId);
            }
        }
        return $count;
    }

    /**
     * 用户是否拥有
     * @return bool
     * @throws \RedisException
     */
    public function getUserHasAttribute(): bool
    {
        $course = Qh_Course::find($this->courseId);
        if ($course) {
            if ($course->amount == 0) return true;
        }

        if (Auth::guard('api')->check()) {
            $user = Auth::guard('api')->user();
            // 查询用户是否拥有了
            // $userCourseIds = DB::table('qh_user_has_course')->where('userId', $user->id)->pluck('courseId')->toArray();
            $userCourseIds = (new RedisBaseService())->getUserHadCourseIds($user->id);
            if (in_array($this->courseId, $userCourseIds)) return true;
        }

        return false;
    }

    public function modelFilter(): ?string
    {
        return $this->provideFilter(Qh_KnowledgeFilter::class);
    }

    public function questionLibrary(): BelongsTo
    {
        return $this->belongsTo(Qh_QuestionLibrary::class, 'qlId');
    }

    public function course(): BelongsTo
    {
        return $this->belongsTo(Qh_Course::class, 'courseId');
    }

    public function parent(): BelongsTo
    {
        return $this->belongsTo(Qh_Knowledge::class, 'parentId');
    }

    public function children(): HasMany
    {
        return $this->hasMany(Qh_Knowledge::class, 'parentId');
    }

    public function getParentNameAttribute() {
        if ($this->level == 1) return null;
        $k1 = Qh_Knowledge::where('id', $this->parentId)->where('level', 1)->first();
        if (!$k1) return null;
        return $k1->name;
    }

    public function getCourseNameAttribute() {
        if ($this->course) return $this->course->name;
        else return null;
    }

    public function kaoshiResult(): HasOne
    {
        return $this->hasOne(Qh_KaoshiResult::class, 'knowledgeId');
    }

    public function getKaoshiResultIdAttribute() {
        if (Auth::guard('api')->check()) {
            $user = Auth::guard('api')->user();
            return DB::table('qh_kaoshi_results_update')->where('userId', $user->id)->where('knowledgeId', $this->id)->value('id');
        }
        return null;
    }

    public function getKaoshiResultAttribute() {
        if ($this->kaoshiMode == 1) {
            if (Auth::guard('api')->check()) {
                $user = Auth::guard('api')->user();
                return $this->kaoshiResult()->where('userId', $user->id)->first();
            }else {
                return null;
            }
        }else {
            return null;
        }
    }

    public function getHasKoashiModeChildAttribute() {
        if ($this->level != 1) return false;
        return (bool)$this->children()->where('kaoshiMode', 1)->first();
    }
}
